package com.jiyici;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.Window;
import com.jiyici.controller.ServerAsyncTask;
import com.jiyici.controller.DataManager;
import com.jiyici.model.ModelUtil;
import com.jiyici.model.User;
import com.jiyici.network.Result;
import com.jiyici.network.WebClientFactory;
import com.jiyici.utils.Global;
import com.jiyici.utils.NotificationUtil;
import com.jiyici.utils.StringUtils;

public class StartActivity extends SherlockFragmentActivity {

    int mPage;

    static final int NUM_ITEMS = 2;

    MyAdapter mAdapter;

    ViewPager mPager;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(R.string.actionbar_item_create_accout).setIcon(R.drawable.ic_action_add_person)
                .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
        menu.add(R.string.actionbar_item_sign_in).setShowAsAction(
                MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (getText(R.string.actionbar_item_create_accout).equals(item.getTitle())) {
            mPager.setCurrentItem(ArrayListFragment.PAGE_REGISTER);
            return true;
        } else if (getText(R.string.actionbar_item_sign_in).equals(item.getTitle())) {
            mPager.setCurrentItem(ArrayListFragment.PAGE_LOGIN);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
        GlobalTheme.applyTheme(this, false);

        super.onCreate(savedInstanceState);

        Global.APP_CONTEXT = getApplicationContext();
        
        User user = DataManager.getUser();
        if (user != null && user.id > 0) {
            Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
            startActivity(intent);
            finish();
        }

        setContentView(R.layout.activity_start);

        mAdapter = new MyAdapter(getSupportFragmentManager());

        mPager = (ViewPager) findViewById(R.id.pager);
        mPager.setAdapter(mAdapter);
        mPager.setOnPageChangeListener(new OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg0) {
                mPage = arg0;
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {

            }
        });

    }

    public static class MyAdapter extends FragmentPagerAdapter {

        public MyAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return NUM_ITEMS;
        }

        @Override
        public Fragment getItem(int position) {
            return ArrayListFragment.newInstance(position);
        }
    }

    public static class ArrayListFragment extends SherlockFragment {
        static final int PAGE_REGISTER = 1;
        static final int PAGE_LOGIN = 0;
        int mNum;

        /**
         * Create a new instance of CountingFragment, providing "num" as an
         * argument.
         */
        static ArrayListFragment newInstance(int num) {
            ArrayListFragment f = new ArrayListFragment();

            // Supply num input as an argument.
            Bundle args = new Bundle();
            args.putInt("num", num);
            f.setArguments(args);

            return f;
        }

        /**
         * When creating, retrieve this instance's number from its arguments.
         */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            mNum = getArguments() != null ? getArguments().getInt("num") : 1;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            int layoutId = 0;
            if (mNum == PAGE_REGISTER)
                layoutId = R.layout.view_register;
            else if (mNum == PAGE_LOGIN)
                layoutId = R.layout.view_login;
            View view = View.inflate(getActivity(), layoutId, null);
            if (mNum == PAGE_REGISTER) {
                final ViewGroup layout = (ViewGroup) view.findViewById(R.id.register_container);
                View btnRegister = view.findViewById(R.id.button_register);
                final EditText editEmail = (EditText) view.findViewById(R.id.edit_email);
                final EditText editUserName = (EditText) view.findViewById(R.id.edit_userName);
                final EditText editPassword = (EditText) view.findViewById(R.id.edit_password);
                btnRegister.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        final String email = editEmail.getText().toString().trim();
                        final String userName = editUserName.getText().toString().trim();
                        final String password = editPassword.getText().toString().trim();
                        if (StringUtils.isBlank(email)) {
                            editEmail.requestFocus();
                            NotificationUtil.notifyError(layout, R.string.user_error_field_blank);
                            return;
                        }
                        if (StringUtils.isBlank(userName)) {
                            editUserName.requestFocus();
                            NotificationUtil.notifyError(layout, R.string.user_error_field_blank);
                            return;
                        }
                        if (StringUtils.isBlank(password)) {
                            editPassword.requestFocus();
                            NotificationUtil.notifyError(layout, R.string.user_error_field_blank);
                            return;
                        }
                        if (!StringUtils.isEmail(email)) {
                            editEmail.requestFocus();
                            NotificationUtil.notifyError(layout, R.string.user_error_invalid_email);
                            return;
                        }
                        new ServerAsyncTask(getActivity(), layout, true) {

                            @Override
                            protected void onSuccess(Result result) {
                                onSignIn(result);
                            }

                            @Override
                            protected Result doRequest() {
                                return WebClientFactory.WebClient.register(email, userName, password);
                            }
                        }.start();
                    }
                });
            } else if (mNum == PAGE_LOGIN) {
                final ViewGroup layout = (ViewGroup) view.findViewById(R.id.login_container);
                View btnSignIn = view.findViewById(R.id.button_login);
                final EditText editEmail = (EditText) view.findViewById(R.id.edit_email);
                final EditText editPassword = (EditText) view.findViewById(R.id.edit_password);
                btnSignIn.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        final String email = editEmail.getText().toString().trim();
                        final String password = editPassword.getText().toString().trim();
                        if (StringUtils.isBlank(email)) {
                            editEmail.requestFocus();
                            NotificationUtil.notifyError(layout, R.string.user_error_field_blank);
                            return;
                        }
                        if (StringUtils.isBlank(password)) {
                            editPassword.requestFocus();
                            NotificationUtil.notifyError(layout, R.string.user_error_field_blank);
                            return;
                        }
                        if (!StringUtils.isEmail(email)) {
                            editEmail.requestFocus();
                            NotificationUtil.notifyError(layout, R.string.user_error_invalid_email);
                            return;
                        }
                        new ServerAsyncTask(getActivity(), layout, true) {

                            @Override
                            protected void onSuccess(Result result) {
                                onSignIn(result);
                            }

                            @Override
                            protected Result doRequest() {
                                return WebClientFactory.WebClient.login(email, password);
                            }
                        }.start();
                    }
                });
            }
            return view;
        }

        private void onSignIn(Result result) {
            User user = ModelUtil.json2User(result.getData());
            if (user == null) {
                NotificationUtil.notifyError(getActivity(), R.string.error_request);
                return;
            }
            DataManager.saveUser(user);
            Intent intent = new Intent(getActivity().getApplicationContext(), HomeActivity.class);
            getActivity().startActivity(intent);
            getActivity().finish();
        }

    }

}
